import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {

  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.checkLogin();
  }

  checkLogin(): boolean {

    // 判断本地有没有token
    const user_token = JSON.parse(window.localStorage.getItem('USER_TOKEN'))
    const token = user_token ? user_token.token : false
    const end_expires = user_token ? user_token.expires : false
    const start_expires = new Date().getTime()
    if (user_token && (end_expires <= start_expires)) {
      window.localStorage.removeItem('USER_TOKEN')
      this.router.navigate(['/login'])
      return false
    }

    // 如果token有值，表示登录成功，继续跳转，否则跳转到首页

    if (user_token && token) { return true }

    this.router.navigate(['/login'])
    return false;
  };
}
